const { think } = require('thinkjs');

module.exports = class extends think.Service {
  async wxappletPay(data) {
    const Tenpay = require('tenpay');
    const config = {
      appid: think.config('gongzhong.AppID'),
      mchid: think.config('gongzhong.mch_id'),
      partnerKey: think.config('gongzhong.partner_key'),
      notify_url: think.config('gongzhong.notify_url'),
      refund_url: think.config('gongzhong.refund_url')
    };
    const api = new Tenpay(config, true);

    const res = await api.unifiedOrder({
      out_trade_no: data['out_trade_no'],
      body: '北京中算' + data['out_trade_no'],
      total_fee: data['total_fee'],
      trade_type: 'NATIVE',
      product_id: '13'
    });
    // {prepay_id, code_url}
    return res.code_url;
  }
  // 微信小程序退款
  async wxappletRefund(orderNumber, orderMoney, orderRefundNumber) {
    const Tenpay = require('tenpay');
    const pfx = require('fs').readFileSync('pem/apiclient_cert.p12');// 小程序证书路径
    const config = {
      appid: think.config('wechat.AppID'),
      mchid: think.config('wechat.mch_id'),
      partnerKey: think.config('wechat.partner_key'),
      pfx: pfx,
      notify_url: think.config('wechat.notify_url'),
      refund_url: think.config('wechat.refund_url'),
      spbill_create_ip: this.ip
    };
      // console.error(config);
    const api = new Tenpay(config);
    // 'refund_account': 'REFUND_SOURCE_RECHARGE_FUNDS',// 退款方式：余额退款
    const result = await api.refund({
      'out_trade_no': orderNumber,
      'out_refund_no': orderRefundNumber,
      'total_fee': orderMoney,
      'refund_fee': orderMoney
    });
    return result;
  }
};
